﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace SWDataDB.DAL
{
    public class DataSet2Json
    {
        public static string DataSetToJson(DataSet ds)
        {
            string json;
            try
            {
                if (ds.Tables.Count == 0)
                    throw new Exception("DataSet中Tables为0");
                json = "[";
                for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                {
                    json += "{";
                    for (int k = 0; k < ds.Tables[0].Columns.Count; k++)
                    {
                        json += ds.Tables[0].Columns[k].ColumnName + ":'" + ds.Tables[0].Rows[j][k] + "'";
                        if (k != ds.Tables[0].Columns.Count - 1)
                            json += ",";
                    }
                    json += "}";
                    if (j != ds.Tables[0].Rows.Count - 1)
                        json += ",";
                }
                
                json += "]";

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return json;  
        }
    }
}
